import {defineStore} from "pinia";
import {reqLogin, reqUserInfo} from "@/api/user/apiUserIndex.ts";
import type {loginForm} from "@/api/user/apiUserType.ts";
import {loginResponseData} from "../../api/user/apiUserType";
import type {UserState} from "./types/typeStore";
import {set_token, get_token,remove_toke} from "../../utils/token";
import {constantRoutes} from "@/router/index.js"
import {useRoute, useRouter} from "vue-router";
let $router=useRouter();
let $route = useRoute();
export const useUserStore = defineStore('UserStore', {
    state: (): UserState => ({
            count: 0,
            items: [],
            token: get_token("TOKEN"),
            menuRoutes: constantRoutes,
            username: '',
            avatar: '',
        }
    ),
    actions: {
        async userLogin(data: loginForm) {
            this.count++;
            let result: loginResponseData = await reqLogin(data);//后面的代码会等待reqLogin执行完成后再执行，后面的代码不会立即执行
            if (result.code === 200) {
                this.token = (result.data.token as string);
                set_token(this.token);
                //localStorage.setItem("TOKEN", (result.data.token) as string);
                return 'ok';
            } else {
                return Promise.reject(new Error(result.data.message));
            }
        },
        async userInfo() {
            console.log("userStore.userInfo is called ,before await reqUserInfo()--")
            let result = await reqUserInfo();
            //console.log(result);
            if (result.code === 200) {
                this.userName = result.data.checkUser.username;
                this.avatar = result.data.checkUser.avatar;
                return 'ok';
            } else {
                return Promise.reject(new Error('获取用户信息失败'));

            }
        },
        userLogout(){
            //目前没有mock的对应接口（通知服务器本地用户的tonken作废
            this.token='';
            this.username='';
            this.avatar='';
            remove_toke();
            $router.push({
                path:'/login',
                query:{
                    redirect:$route.path
                }
            });

        }
    }
})



